package com.csun.cmny.provider.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.constant.Constant;
import com.csun.cmny.provider.dto.SetMealSaveParameterDto;
import com.csun.cmny.provider.model.domain.OmcOldManAccountFunds;
import com.csun.cmny.provider.model.domain.OmcSetMeal;
import com.csun.cmny.provider.model.vo.ExpenseTypeAllVo;
import com.csun.cmny.provider.model.vo.SetMealVo;
import com.csun.cmny.provider.pojo.*;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.vo.SetMealSaveItemVo;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 * 护理管理
 * */
@RestController
@RequestMapping("/nurse")
public class NurseController extends BaseController {
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private OldmanNurseService oldmanNurseService;
    @Autowired
    private ExpCtrItemService expCtrItemService;
    @Autowired
    private OldmanTendService oldmanTendService;
    @Autowired
    private OldmanService oldmanService;
    @Autowired
    private OldmanNurseHiService oldmanNurseHiService;
    @Resource
    private OmcExpenseTypeService omcExpenseTypeService;
    @Resource
    private OmcSetMealService omcSetMealService;
    @Resource
    private OmcOldManAccountFundsService omcOldManAccountFundsService;
    @Resource
    private CmnyMessageSource cmnyMessageSource;

    /**
     *
     * 查询护理列表
     * @param queryMap
     * @return
     */
    @RequestMapping(value = "/showCheckInOldManInfo", method = RequestMethod.POST)
    public Wrapper showCheckInOldManInfo(@RequestBody Map<String,Object> queryMap) {
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //当前登录用户获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        queryMap.put("homeId", loginAuthDto.getGroupId());
        PageHelper.startPage(Integer.valueOf(pageNo),Integer.valueOf(pageSize));
        //查询已入院的老人基本信息列表
        List<OldmanInfo> checkInList =  oldmanTendService.getAllTends(queryMap);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<OldmanItemVo> oldmanItemVoList = null;
        for (OldmanInfo in:checkInList) {
           oldmanItemVoList = new ArrayList<>();
            OldmanNurseHi oldmanNurseHi = oldmanNurseHiService.selectRecentNurse(in.getOldmanId());
            if(oldmanNurseHi!=null && oldmanNurseHi.getNurseDate()!=null){
               in.setNurseDate(simpleDateFormat.format(oldmanNurseHi.getNurseDate()));
           }
           in.setOldmanItemVoList(oldmanItemVoList);
         }
        PageInfo<OldmanInfo> pageInfo = new PageInfo<>(checkInList);
//        return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), pageInfo);
    }

    /**
     * 根据Id删除老人护理
     * @param tendId
     * @return
     */
    @RequestMapping(value="/deleteTendById",method = RequestMethod.POST)
    public Wrapper deleteTendById(@Param("tendId") Integer tendId){
        //参数校验
        if (tendId == null) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"护理Id不可为空",null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,cmnyMessageSource.getMessage("nursing.id.null", null),null);
        }
        OldmanTend oldmanTend =  oldmanTendService.selectByPrimaryKey(tendId);
        if (oldmanTend == null){
//            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"id不存在",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("nursing.not.exsit", null),null);
        }
        //判断老人状态，只有出院才能删除
        Oldman newoldman = new Oldman();
        newoldman.setOldmanId(oldmanTend.getOldmanId());
        Oldman oldman =  oldmanService.selectByOld(newoldman);
        if (oldman.getStatus().equals(Constant.YICHUYUAN)){
           int n =  oldmanTendService.deleteByPrimaryKey(tendId);
           if(n>0){
//               return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"删除成功",tendId);
               return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),tendId);
           }else {
//               return WrapMapper.wrap(Wrapper.ERROR_CODE,"删除失败",n);
               return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("operation.failed", null),n);
           }
        }else {
//            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该老人未出院，不可删除",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("oldman.not.out", null),null);
        }
    }
    /**
     * 点击护理图标获取套餐集合
     */
    @RequestMapping(value="/getSetMeals",method = RequestMethod.POST)
    public Wrapper getSetMeals(@Param("expensectrType") String expensectrType ){
        //参数校验
        if (StringUtils.isEmpty(expensectrType)) {
//            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"费用类型不可为空",null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,cmnyMessageSource.getMessage("expense.type.null", null),null);
        }
        Map map = new HashMap();

        Map<String,Object> query = new HashMap<>();
        query.put("expensectrType",expensectrType);
        query.put("homeId",getLoginAuthDto().getGroupId());
        if (expensectrType.equals(Constant.CANYIN)){
            //查询餐饮套餐
            List<SetMeal> canyinList= setMealService.getMealsByExpensectrType(query);
            map.put("canyinList",canyinList);
        }
        if (expensectrType.equals(Constant.CHUANGWEI)) {
            //查询床位套餐
            List<SetMeal> chuangweiList = setMealService.getMealsByExpensectrType(query);
            map.put("chuangweiList",chuangweiList);
        }
        if (expensectrType.equals(Constant.HULI)) {
            //查询护理套餐
            List<SetMeal> huliList = setMealService.getMealsByExpensectrType(query);
            map.put("huliList",huliList);
        }
        if (expensectrType.equals(Constant.GEXING)) {
            //查询私人定制项目
            List<ExpCtrItem> gexingList = expCtrItemService.setlectItemByExpensectrType(query);
            map.put("gexingList",gexingList);
        }
//        return WrapMapper.ok(map);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),map);
    }


    /**
     * 查询护理列表(乐怡版)
     */
    @RequestMapping(value = "/showOldManInfo", method = RequestMethod.POST)
    public Wrapper showOldManInfo(@RequestBody Map<String,Object> queryMap) {
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");
        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //当前登录用户获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        queryMap.put("homeId", loginAuthDto.getGroupId());
        PageHelper.startPage(Integer.valueOf(pageNo),Integer.valueOf(pageSize));
        //查询已入院的老人基本信息列表
        List<OldmanInfo> checkInList =  oldmanTendService.getAllOldman(queryMap);
        PageInfo<OldmanInfo> pageInfo = new PageInfo<>(checkInList);
//        return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }

    /**
     * 套餐合并
     */
    @RequestMapping(value="/getAllSetMeals",method = RequestMethod.POST)
    public Wrapper getAllSetMeals(){
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Long groupId = loginAuthDto.getGroupId();
        List<ExpenseTypeAllVo> expenseTypeVoList = omcExpenseTypeService.queryTypeAll(groupId);
//        return WrapMapper.ok(expenseTypeVoList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),expenseTypeVoList);
    }

    /**
     * 根据机构ID查询项目及套餐详情
     * @return
     */
    @RequestMapping(value="/selectSetMealById",method = RequestMethod.POST)
    public Wrapper selectSetMealById(@RequestBody OmcSetMeal omcSetMeal){
        omcSetMeal.setStatus(1);
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        omcSetMeal.setGroupId(loginAuthDto.getGroupId());
        List<OmcSetMeal> setMeal = omcSetMealService.queryAll(omcSetMeal);
//        return WrapMapper.ok(setMeal);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),setMeal);
    }

    /**
     * 添加更改护理记录乐颐版
     * @return
     */
    @RequestMapping(value="/updateAllById",method = RequestMethod.POST)
    public Wrapper updateAllById(@RequestBody SetMealSaveParameterDto setMealSaveParameterDto,Long groupId) {
        //校验用户是否选择了项目
        if(setMealSaveParameterDto.getSetMealSaveItemVo() == null || setMealSaveParameterDto.getSetMealSaveItemVo().size()<1){
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,cmnyMessageSource.getMessage("nursing.is.null", null),null);
        }
        if (StringUtils.isEmpty(setMealSaveParameterDto.getOldmanId())) {
//            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"老人id不能为空！",null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,cmnyMessageSource.getMessage("oldman.id.null", null),null);
        }
        //保存或者更改护理项目
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        groupId = loginAuthDto.getGroupId();
        Long oldmanId = setMealSaveParameterDto.getOldmanId();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String updateTime = sdf.format(date);
        Map<String,Object> map = new HashMap<>();
        map.put("oldmanId",oldmanId);
        map.put("groupId",groupId);
        map.put("updateTime",updateTime);

        //查询该老人的余额和消费总额
        Long oldManId = setMealSaveParameterDto.getOldmanId();
        OmcOldManAccountFunds omcOldManAccountFunds =new OmcOldManAccountFunds();
        omcOldManAccountFunds.setOldManId(oldManId);
        omcOldManAccountFunds.setGroupId(groupId);
        OmcOldManAccountFunds omc = omcOldManAccountFundsService.selectOne(omcOldManAccountFunds);

        if (PublicUtil.isEmpty(omc)){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("oldMan.account.funds.null", null));
        }

        //获取添加或者修改前余额
        BigDecimal remainder = omc.getRemainder();
        //获取添加或者修改前消费总额
        BigDecimal monetary = omc.getMonetary();
        //修改人和修改人ID
        omcOldManAccountFunds.setLastOperator(loginAuthDto.getUserName());
        omcOldManAccountFunds.setLastOperatorId(loginAuthDto.getUserId());
        //查询老人天的护理详情
        SetMealSaveParameterDto oneList = oldmanNurseHiService.selectByIdDay(map);
        //判断该老人当天是否已选择项目,已选择则删除今天的数据
        if(oneList != null){
            //查询今天护理套餐的消费,并根据消费将余额和消费总额修改到更改前
            BigDecimal totalPrice = oneList.getTotalPrice();
            remainder = remainder.add(totalPrice);
            monetary = monetary.subtract(totalPrice);

            //删除该老人ID下的今天数据
          int all = oldmanNurseHiService.deleteAllById(map);
          int item = oldmanNurseHiService.deleteItemById(map);
          if(all<0 || item<0){
//              return  WrapMapper.wrap(Wrapper.ERROR_CODE,"修改失败",all);
              return  WrapMapper.wrap(Wrapper.ERROR_CODE,"comment.change.fail",all);
          }
        }
        //保存老人所选的项目
        setMealSaveParameterDto.setUpdateTime(new Date());
        setMealSaveParameterDto.setGroupId(loginAuthDto.getGroupId());
        setMealSaveParameterDto.setLastOperator(loginAuthDto.getUserName());
        setMealSaveParameterDto.setLastOperatorId(loginAuthDto.getUserId());

        List<SetMealSaveItemVo> setMealSaveItemVo = new ArrayList<>(setMealSaveParameterDto.getSetMealSaveItemVo());
        for (SetMealSaveItemVo s : setMealSaveItemVo ) {
            s.setOldmanId(setMealSaveParameterDto.getOldmanId());
            s.setGroupId(loginAuthDto.getGroupId());
            s.setLastOperator(loginAuthDto.getUserName());
            s.setLastOperatorId(loginAuthDto.getUserId());
            s.setUpdateTime(new Date());
            oldmanNurseHiService.insertAddItem(s);
        }
        int n = oldmanNurseHiService.insertNew(setMealSaveParameterDto);
        if (n <= 0) {
//            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"更改项目失败",n);
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"comment.change.fail",n);
        }
        //查询修改后的消费金额
        SetMealSaveParameterDto afterModified = oldmanNurseHiService.selectByIdDay(map);
        BigDecimal afterTotalPrice = afterModified.getTotalPrice();

        //修改余额和消费金额
         remainder = remainder.subtract(afterTotalPrice);
         monetary = monetary.add(afterTotalPrice);
        //将修改后的余额与消费总额保存到数据库
        omcOldManAccountFunds.setRemainder(remainder);
        omcOldManAccountFunds.setMonetary(monetary);
        //数据不够完整需要单独调用接口修改
        int k = omcOldManAccountFundsService.updatePrice(omcOldManAccountFunds);
        if(k<=0){
//            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"费用修改失败",k);
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"comment.change.fail",k);
        }
//        return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"添加成功",n);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),k);
    }

    /**
     * 根据老人ID查询详情
     * @param queryMap
     * @return
     */
    @RequestMapping(value="/getAllById",method = RequestMethod.POST)
    public Wrapper getAllById(@RequestBody Map<String,Object> queryMap) {
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");
        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        queryMap.put("groupId",loginAuthDto.getGroupId());
        List<SetMealSaveParameterDto> list = oldmanNurseHiService.selectAll(queryMap);
        List<SetMealSaveItemVo> setMealSaveItemVoList= null;
        for (SetMealSaveParameterDto s: list) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Map<String,Object> map = new HashMap<>();
            map.put("oldmanId",s.getOldmanId());
            map.put("groupId",loginAuthDto.getGroupId());
            map.put("updateTime",sdf.format(s.getUpdateTime()));
            setMealSaveItemVoList = oldmanNurseHiService.selectItem(map);
            s.setSetMealSaveItemVo(setMealSaveItemVoList);
        }
        SetMealVo setMeal = null;
        for (SetMealSaveParameterDto d : list) {
            if(d.getSetmealId()!=null && d.getSetmealId()>0) {
                Long setMealId = d.getSetmealId();
                setMeal = omcSetMealService.getById(setMealId);
                if (setMeal != null) {
                    d.setSetMealVo(setMeal);
                }
            }
        }
        PageInfo<SetMealSaveParameterDto> pageInfo = new PageInfo<>(list);
//        return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }

    /**
     * 根据老人Id查询老人当天的护理详情
     */
    @RequestMapping(value="/selectByoldmanId",method = RequestMethod.POST)
    public Wrapper selectByoldmanId(@RequestBody Map<String,Object> queryMap){
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        queryMap.put("groupId",loginAuthDto.getGroupId());
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String updateTime = sdf.format(date);
        queryMap.put("updateTime",updateTime);
        SetMealSaveParameterDto oneList = oldmanNurseHiService.selectByIdDay(queryMap);
        List<SetMealSaveItemVo> setMealSaveItemVoList= null;
        if(oneList!=null) {
            Map<String, Object> map = new HashMap<>();
            map.put("oldmanId", oneList.getOldmanId());
            map.put("groupId", loginAuthDto.getGroupId());
            map.put("updateTime", updateTime);
            setMealSaveItemVoList = oldmanNurseHiService.selectItem(map);
            oneList.setSetMealSaveItemVo(setMealSaveItemVoList);
        }
//        return WrapMapper.ok(oneList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),oneList);
    }

    /**
     * 添加护理记录（每天修改记录）
     */
    @RequestMapping(value="/addNurseRecord",method = RequestMethod.POST)
    public Wrapper addNurseRecord(@RequestBody OldmanNurse nurse){
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        OldmanNurseHi oldmanNurseHi = new OldmanNurseHi();
        oldmanNurseHi.setNurseDate(new Date());
        oldmanNurseHi.setCreateTime(new Date());
        oldmanNurseHi.setCreator(loginAuthDto.getGroupId().intValue());

        //参数校验
        if (StringUtils.isEmpty(nurse.getOldmanId())) {
            //            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"老人id不能为空！",null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,cmnyMessageSource.getMessage("oldman.id.null", null),null);
        }
        oldmanNurseHi.setOldmanId(nurse.getOldmanId());
        if(nurse.getBreakfast()==null && nurse.getLunch()==null && nurse.getDinner()==null && nurse.getBed()==null && nurse.getNurse()==null && (nurse.getOldmanItemList()==null || nurse.getOldmanItemList().size()<=0)){
//            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"请选择至少一个护理项目！",null);
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,cmnyMessageSource.getMessage("nursing.is.null", null),null);
        }

        // 校验老人是否在院
        Oldman oldmanQuery = new Oldman();
        oldmanQuery.setOldmanId(nurse.getOldmanId());
        oldmanQuery = oldmanService.selectByOld(oldmanQuery);
        if (!oldmanQuery.getStatus().equals(Constant.YIRUYUAN)) {
//            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"老人不是入院状态",null);
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,cmnyMessageSource.getMessage("oldman.not.in", null),null);
        }

        BigDecimal zaocanFee = new  BigDecimal(0);
        SetMeal setMeal = null;
        //根据套餐id查询该套餐费用
        if (nurse.getBreakfast()!= null){
            setMeal = setMealService.selectById(nurse.getBreakfast());
            if(PublicUtil.isNotEmpty(setMeal)){
                zaocanFee = setMeal.getAfterDis();
                oldmanNurseHi.setBreakfast(setMeal.getSetMealName()+"/"+setMeal.getAfterDis()+"元");
            }
        }else {
            oldmanNurseHi.setBreakfast("无");
        }
        BigDecimal zhongcanFee = new  BigDecimal(0);
        if (nurse.getLunch() != null){
            setMeal = setMealService.selectById(nurse.getLunch());
            if (PublicUtil.isNotEmpty(setMeal)) {
                zhongcanFee = setMeal.getAfterDis();
                oldmanNurseHi.setLunch(setMeal.getSetMealName()+"/"+setMeal.getAfterDis()+"元");
            }
        }else {
            oldmanNurseHi.setLunch("无");
        }
        BigDecimal wancanFee =new  BigDecimal(0);
       if (nurse.getDinner()!=null){
           setMeal = setMealService.selectById(nurse.getDinner());
           if (PublicUtil.isNotEmpty(setMeal)) {
               wancanFee = setMeal.getAfterDis();
               oldmanNurseHi.setDinner(setMeal.getSetMealName()+"/"+setMeal.getAfterDis()+"元");
           }
       }else {
           oldmanNurseHi.setDinner("无");
       }
        BigDecimal bedFee = new  BigDecimal(0);
       if (nurse.getBed() != null){
           setMeal = setMealService.selectById(nurse.getBed());
           if (PublicUtil.isNotEmpty(setMeal)) {
               bedFee = setMeal.getAfterDis();
               oldmanNurseHi.setBed(setMeal.getSetMealName()+"/"+setMeal.getAfterDis()+"元");
           }
       }else {
           oldmanNurseHi.setBed("无");
       }
        BigDecimal huliFee = new  BigDecimal(0);
       if (nurse.getNurse()!= null){
           setMeal = setMealService.selectById(nurse.getNurse());
           if (PublicUtil.isNotEmpty(setMeal)) {
               huliFee = setMeal.getAfterDis();
               oldmanNurseHi.setNurseFee(setMeal.getSetMealName()+"/"+setMeal.getAfterDis()+"元");
           }
       }else {
           oldmanNurseHi.setNurseFee("无");
       }

        List<OldmanItem> oldmanItemList = new ArrayList<>();
        BigDecimal totalFee = null;
       if (nurse.getOldmanItemList()!=null){
           //个性化套餐总和
           BigDecimal gexingFee=new  BigDecimal(0);
           JSONArray jsonArray = JSONArray.fromObject(nurse.getOldmanItemList());
           ExpCtrItem expCtrItem = null;
           StringBuffer expCtrItemStr = new StringBuffer();
           for (int i =0;i<jsonArray.size();i++) {
               OldmanItem oldmanItem = JSONObject.parseObject(jsonArray.getJSONObject(i).toString(), OldmanItem.class);
               oldmanItem.setModifier(loginAuthDto.getUserId());
               gexingFee=gexingFee.add(oldmanItem.getItemPrice());
               oldmanItemList.add(oldmanItem);
               expCtrItem = expCtrItemService.selectById(jsonArray.getJSONObject(i).getInt("itemId"));
               expCtrItemStr.append(expCtrItem.getItemName()+"/"+expCtrItem.getChargeStandard());
               switch (expCtrItem.getCostType()){
                   case 1:
                       expCtrItemStr.append("元/次;");
                       break;
                   case 2:
                       expCtrItemStr.append("元/天;");
                       break;
                   case 3:
                       expCtrItemStr.append("元/月;");
                       break;
                   case 4:
                       expCtrItemStr.append("元/年;");
                       break;
                   case 5:
                       expCtrItemStr.append("元/一次性;");
                       break;
               }
           }
           oldmanNurseHi.setSetMeal(expCtrItemStr.toString());
           totalFee = zaocanFee.add(zhongcanFee).add(wancanFee).add(bedFee).add(huliFee).add(gexingFee);
           nurse.setTotalFee(totalFee);
           String jsonData = JSON.toJSONString(oldmanItemList);
           nurse.setJsonData(jsonData);
           oldmanNurseHi.setTotalFee(totalFee+"元");
           //费用结算
           oldmanNurseService.saveOrUpdateFee(nurse,loginAuthDto);
       }
        //添加或更新护理记录
        oldmanNurseHiService.insert(oldmanNurseHi);
//       return WrapMapper.ok();
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),null);
    }
    /**
     * 查看老人护理清单
     */
    @RequestMapping(value="/getDetailById",method = RequestMethod.POST)
    public Wrapper getDetailById(@RequestBody Map<String,Object> queryMap){
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");
        String oldmanId = (String) queryMap.get("oldmanId");

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //参数校验
        if (StringUtils.isEmpty(oldmanId)){
            //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"老人id不能为空！",null);
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,cmnyMessageSource.getMessage("oldman.id.null", null),null);
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
       List<OldmanNurse> nurseList= oldmanNurseService.selectByOldmanIdOrderByNurseDate(queryMap);
       BigDecimal  sumFee = BigDecimal.ZERO;//总计
        List<ExpCtrItem> expCtrItemList = null;//老人私人订制项目集合
        for (OldmanNurse nurse:nurseList) {
            expCtrItemList = new ArrayList<>();
            //将字符串转成java对象
            if (!StringUtils.isEmpty(nurse.getJsonData())){
                String jsonData = nurse.getJsonData();
                System.out.print("jsonData:"+jsonData);
                JSONArray jsonArray = JSONArray.fromObject(jsonData);
                List<OldmanItemVo> oldmanItemVoList =  JSONArray.toList(jsonArray,OldmanItemVo.class);
                for (OldmanItemVo oldmanItemVo:oldmanItemVoList) {
                    ExpCtrItem expCtrItem = expCtrItemService.selectById(oldmanItemVo.getItemId());
                    expCtrItemList.add(expCtrItem);
                }
            }
            nurse.setExpCtrItemList(expCtrItemList);
            sumFee=sumFee.add(nurse.getTotalFee()==null?new BigDecimal(0):nurse.getTotalFee());
            SetMeal breakfastSetMeal = setMealService.selectById(nurse.getBreakfast());
            if (breakfastSetMeal !=null){
                nurse.setBreakfastSetMealName(breakfastSetMeal.getSetMealName());
                nurse.setBreakfastAfterDis(breakfastSetMeal.getAfterDis());
            }

            SetMeal lunchSetMeal = setMealService.selectById(nurse.getLunch());
            if(lunchSetMeal != null){
                nurse.setLunchSetMealName(lunchSetMeal.getSetMealName());
                nurse.setLunchAfterDis(lunchSetMeal.getAfterDis());
            }


            SetMeal dinnerSetMeal = setMealService.selectById(nurse.getDinner());
            if (dinnerSetMeal != null ){
                nurse.setDinnerSetMealName(dinnerSetMeal.getSetMealName());
                nurse.setDinnerAfterDis(dinnerSetMeal.getAfterDis());
            }


            SetMeal bedSetMeal = setMealService.selectById(nurse.getBed());
            if (bedSetMeal != null){
                nurse.setBedSetMealName(bedSetMeal.getSetMealName());
                nurse.setBedAfterDis(bedSetMeal.getAfterDis());
            }


            SetMeal nurseSetMeal = setMealService.selectById(nurse.getNurse());
            if (nurseSetMeal != null ){
                nurse.setNurseSetMealName(nurseSetMeal.getSetMealName());
                nurse.setNurseAfterDis(nurseSetMeal.getAfterDis());
            }

        }
        PageInfo<OldmanNurse> pageInfo = new PageInfo<>(nurseList);
        Map map = new HashMap();
        map.put("sumFee",sumFee);
        map.put("nurseList",pageInfo);
//        return WrapMapper.ok(map);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),map);
    }

    /**
     * 获取老人所有护理记录
     * @param queryMap
     * @return
     */
    @RequestMapping(value="/getAllHistoryData",method = RequestMethod.POST)
    public Wrapper getAllHistoryData(@RequestBody Map<String,Object> queryMap){
        if(queryMap.get("oldmanId")==null){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"老人ID不能为空！",null);
        }
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");
        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize),"nurseDate desc");
        List<OldmanNurseHi> oldmanNurseHiList = oldmanNurseHiService.getAllHistoryByOldmanId((int) queryMap.get("oldmanId"));
        PageInfo<OldmanNurseHi> pageInfo = new PageInfo<>(oldmanNurseHiList);
//        return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }
}
